#include "png8cropfx.h"
#include "png8source.h"

namespace png8crop
{
	png8source::png8source(FILE* src) throw(ex_generic)
	{
		try
		{
			this->load(src);
		}
		catch(ex_generic ex)
		{
			this->~png8source();

			ex.print_msg();
			throw;
		}
	}

	png8source::~png8source(void)
	{
		png_destroy_read_struct(&this->ptr, &this->info, NULL);
	}

	void png8source::load(FILE* src)
	{
		try
		{
			this->ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
			this->info = png_create_info_struct(this->ptr);

			png_init_io(this->ptr, src);

			int interlace_type, compression_type, filter_type;
			png_uint_32 iRet;

			if (setjmp(png_jmpbuf(this->ptr)))
			{
				throw ex_io(_T("png file read error."));
			}

			//read data
			png_read_png(this->ptr, this->info, 0, NULL);

			//verification input
			iRet = png_get_IHDR(this->ptr, this->info, &this->size.w, &this->size.h, &this->bit_depth,
				&this->color_type, &interlace_type, &compression_type, &filter_type);
			iRet = iRet && png_get_PLTE(this->ptr, this->info, &this->palette, &this->num_palette);
			iRet = iRet && png_get_tRNS(this->ptr, this->info, &this->trans_alpha,
				&this->num_trans, &this->trans_color);

			if(!iRet || this->color_type != PNG_COLOR_TYPE_PALETTE || this->bit_depth != 8)
			{
				throw ex_dataformat(_T("a palettized png8 required."));
			}

			this->rows = png_get_rows(this->ptr, this->info);

		}
		catch(...)
		{
			png_destroy_read_struct(&this->ptr, &this->info, NULL);

			throw;
		}
	}
}
